package vn.buffalocoders.rikos.ui.network;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import vn.buffalocoders.rikos.ui.common.CryptographyUtility;
import vn.buffalocoders.rikos.ui.common.RikoBook;
import vn.buffalocoders.rikos.ui.common.RikoBookType;
import vn.buffalocoders.rikos.ui.common.RikoCategory;
import vn.buffalocoders.rikos.ui.common.RikoPublisher;
import vn.buffalocoders.rikos.ui.common.RikoUploader;

import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

public class ConnectRikoServer {
	public static final String URL_IMAGE_HOME				= "http://img.riko.vn/";

	public static final String URL_REGISTER					= "http://api.riko.vn/Riko/auth/register";
	public static final String URL_LOGIN 					= "http://api.riko.vn/Riko/auth/login";
	public static final String URL_LOGIN_FACEBOOK 			= "http://api.riko.vn/Riko/auth/login_facebook";
	public static final String URL_LOGOUT 					= "http://api.riko.vn/Riko/auth/logout";
	public static final String URL_UPLOAD_AVATAR			= "http://api.riko.vn/Riko/user/token/upload_avatar";

	public static final String URL_BOOK_LIST_WITH_CATEGORY	= "http://api.riko.vn/Riko/book/token/book_list_with_cate";
	public static final String URL_GET_LIST_CATEGORY		= "http://api.riko.vn/Riko/book/category_list";
	public static final String URL_GET_LIST_COMMENT			= "http://api.riko.vn/Riko/comment/token/list_comment_book";
	public static final String URL_GET_COMMENT_BOOK			= "http://api.riko.vn/Riko/comment/token/comment_book";
	public static final String URL_GET_RANKING				= "http://api.riko.vn/Riko/book/token/ranking";
	public static final String URL_GET_LIST_MY_LIB			= "http://api.riko.vn/Riko/book/token/get_gallerry";
	public static final String URL_GET_LIST_FAVORITE		= "http://api.riko.vn/Riko/book/token/get_list_favorite";
	public static final String URL_GET_LIST_READING			= "http://api.riko.vn/Riko/book/token/get_list_reading";
	public static final String URL_ADD_LIBARY				= "http://api.riko.vn/Riko/book/token/add_libary";
	public static final String URL_COUNT_READED_AND_READING = "http://api.riko.vn/Riko/book/token/count_readed_and_reading";
	public static final String URL_COUNT_DELETE_BOOK_IN_LIB = "http://api.riko.vn/Riko/book/token/delete_book_in_libary";

	// param for Query
	private static final String PARAM_KEY_USERNAME 			= "name";
	private static final String PARAM_KEY_EMAIL 			= "email";
	private static final String PARAM_KEY_PASSWORD 			= "password";
	private static final String PARAM_KEY_AVATAR			= "avatar";
	private static final String PARAM_KEY_PERIOD_TOKEN		= "period_token";
	private static final String PARAM_KEY_FB_ID				= "fb_id";
	private static final String PARAM_KEY_FB_ACCESS_TOKEN 	= "fb_access_token";

	private static final String PARAM_KEY_USER_ID   = "user_id";
	private static final String PARAM_KEY_CATE_ID   = "cate_id";
	private static final String PARAM_KEY_VIEW    	= "view";
	private static final String PARAM_KEY_LIKE 		= "like";
	private static final String PARAM_KEY_PAGE 	   	= "page";
	private static final String PARAM_KEY_LIMIT 	= "limit";
	private static final String PARAM_KEY_NUMBER    = "number";
	private static final String PARAM_KEY_BOOK_ID   = "book_id";

	public static final String PARAM_BOOK_FILE		= "book_file";
	public static final String PARAM_IMAGE_FILE		= "image_file";
	// Param for json
	public static final String RIKO_STATUS_SUCCESS = "success";
	public static final String RIKO_STATUS_FAILED = "failure";


	public static final String RIKO_RESULT_AUTH_TOKEN = "token";
	public static final String RIKO_RESULT_EMAIL = "email";
	public static final String RIKO_RESULT_DEVICE_ID = "deviceId";
	public static final String RIKO_RESULT_PERIOD_TOKEN = "periodToken";
	public static final String RIKO_RESULT_NAME = "name";
	public static final String RIKO_RESULT_PASSWORD = "password";
	public static final String RIKO_RESULT_USER_ID = "id";
	public static final String RIKO_RESULT_CREATE_DATE = "createDate";
	public static final String RIKO_RESULT_STATUS = "status";

	public static final String RIKO_RESULT_CODE = "code";
	public static final String RIKO_RESULT_CAUSE = "cause";

	public static final String RIKO_RESULT_AVATAR = "avatar";
	public static final String RIKO_RESULT_LAST_LOGIN = "lastlogin";
	public static final String RIKO_RESULT_DEVICE_TOKEN = "deviceToken";

	public static final String RIKO_RESULT_DEVICE_FACEBOOK_ID = "fbId";
	public static final String RIKO_RESULT_DEVICE_FACEBOOK_ACCESS_TOKEN = "fbAccessToken";

	public static final String X_RIKO_AUTH_TOKEN = "X-RIKO-Auth-Token";
	public static final String X_RIKO_USER_ID 	= "X-RIKO-USERID";

	private static final String TAG_DEBUG = "LETRUONG";

	private static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the BufferedReader.readLine()
		 * method. We iterate until the BufferedReader return null which means
		 * there's no more data to read. Each line will appended to a StringBuilder
		 * and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	private static JSONObject parseResponseToJson(HttpResponse response) throws IllegalStateException, IOException, JSONException {
		JSONObject json = null;
		// Get hold of the response entity
		HttpEntity entity = response.getEntity();
		// If the response does not enclose an entity, there is no need
		// to worry about connection release
		if (entity != null) {
			// A Simple JSON Response Read
			InputStream instream = entity.getContent();
			String result= convertStreamToString(instream);
			json = new JSONObject(result);
			// Closing the input stream will trigger connection release
			instream.close();
		}

		return json;
	}
	/* This is a test function which will connects to a given
	 * rest service and prints it's response to Android Log with
	 * labels "Rikos".
	 */
	private static JSONObject connectByGetMethod(String url, Map<String, String> headerParams, List<NameValuePair> getParams)
	{
		JSONObject json = null;
		HttpClient httpclient = new DefaultHttpClient();
		// Execute the request
		try {
			String combinedParams = "";
			if(!getParams.isEmpty()){
				combinedParams += "?";
				for(NameValuePair p : getParams)
				{
					String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
					if(combinedParams.length() > 1)
					{
						combinedParams  +=  "&" + paramString;
					}
					else
					{
						combinedParams += paramString;
					}
				}
			}
			// Prepare a request object
			HttpGet httpget = new HttpGet(url + combinedParams); 

			for (Map.Entry<String, String> entry : headerParams.entrySet()) {
				httpget.setHeader(entry.getKey(), entry.getValue());
			}

			HttpResponse response = httpclient.execute(httpget);
			// Examine the response status
			json = parseResponseToJson(response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if (e instanceof ClientProtocolException || 
					e instanceof IOException ||
					e instanceof JSONException) {
				e.printStackTrace();
			} 
			else {
				// throw new RuntimeException(exc);
			}
			return json;
		}
		return json;
	}

	private static JSONObject connectByPostMethod(String url, Map<String, String> headerParams, List<NameValuePair> postParams) {
		JSONObject json = null;
		// Create a new HttpClient and Post Header
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(url);

		try {
			for (Map.Entry<String, String> entry : headerParams.entrySet()) {
				if (entry.getValue().equals("multipart/form-data")) {
					httppost.addHeader("Content-type", "multipart/form-data");
				} else {
					httppost.setHeader(entry.getKey(), entry.getValue());
				}
			}
			// Add your data
			httppost.setEntity(new UrlEncodedFormEntity(postParams));
			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);
			// Examine the response status
			json = parseResponseToJson(response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			if (e instanceof ClientProtocolException || 
					e instanceof IOException ||
					e instanceof JSONException) {
				e.printStackTrace();
			} 
			else {
				// throw new RuntimeException(exc);
			}
			return json;
		}
		return json;
	}

	/*********** GET BOOK WITH CATEGORY ***********/
	
	
	public static ArrayList<RikoBook> getBookJsonObj (JSONObject jsonObj){
		if(jsonObj == null)
			return null;	
		// A Simple JSONObject Parsing
		//	JSONArray booknameArray;
		JSONArray  booksJsonArray;
		JSONObject booksJsonObj;
		Log.i("DBT", String.format("JSON=%s",jsonObj));
		ArrayList<RikoBook> listbook = new ArrayList<RikoBook>();
		int ibook, icate;

		try {	
			if(jsonObj.getString(RikoBook.KEY_STATUS).equals(RIKO_STATUS_FAILED))
			{
				Log.i("DBT", String.format("Status get Book unsuccess %s",jsonObj.getString(RikoBook.KEY_STATUS) ));
				return null;
			}		
			if(jsonObj.isNull(RikoBook.KEY_BOOKS)){
				return null;
			}

			booksJsonArray = jsonObj.getJSONArray(RikoBook.KEY_BOOKS);			 
			if(booksJsonArray == null)
				return null;
			Log.i("DBT", String.format("Length=%d", booksJsonArray.length()));

			for(ibook=0;ibook<booksJsonArray.length();ibook++)
			{	            
				JSONObject bookJsonObj = booksJsonArray.getJSONObject(ibook);
				Log.i("DBT", String.format("Book %s", bookJsonObj));
				// Get Status, createDate, id , name, and title .Create new book
				RikoBook book = new RikoBook();	                
				book.setSummary(bookJsonObj.getString(RikoBook.KEY_BOOKS_SUM));
				Log.i("DBT", String.format("summary %s", bookJsonObj.getString(RikoBook.KEY_BOOKS_SUM)));
				// book.setFileType(RikoBookType.valueOf(bookJsonObj.getString(RikoBook.KEY_BOOKS_FILETYPE)));	 
				//   Log.i("DBT", String.format("fileType %s", bookJsonObj.getString(RikoBook.KEY_BOOKS_FILETYPE)));
				book.setStatus(bookJsonObj.getString(RikoBook.KEY_BOOKS_STATUS));
				Log.i("DBT", String.format("Status %s", bookJsonObj.getString(RikoBook.KEY_BOOKS_STATUS)));

				// Get Uploader and add to new book
				JSONObject uploaderJsonObj = bookJsonObj.getJSONObject(RikoBook.KEY_BOOKS_UP);
				Log.i("DBT", String.format("Uploader %s", uploaderJsonObj));
				/* RikoUploader uploader = new RikoUploader();
                uploader.setId(uploaderJsonObj.getInt(RikoBook.KEY_BOOKS_UP_ID));
                uploader.setLastLogin(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_LASTLOGIN));
                uploader.setEmail(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_EMAIL));
                uploader.setToken(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_TOKEN));
                uploader.setStatus(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_STATUS));
                uploader.setDeviceToken(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_DEVTOKEN));
                uploader.setName(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_NAME));
                uploader.setAvatar(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_AVAT));
                uploader.setCreateDate(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_DATE));
                uploader.setDeviceID(uploaderJsonObj.getString(RikoBook.KEY_BOOKS_UP_DEV));
                book.setUploader(uploader);*/

				/* Get number,viewNum,chapterNum*/	                
				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_NUMBER)){	
					book.setNumber(bookJsonObj.getInt(RikoBook.KEY_BOOKS_NUMBER));
				}
				
				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_VIEW)){
					book.setViewNum(bookJsonObj.getInt(RikoBook.KEY_BOOKS_VIEW));
					Log.i("DBT", String.format("viewNum %d", bookJsonObj.getInt(RikoBook.KEY_BOOKS_VIEW)));
				}
				//  book.setChapterNum(bookJsonObj.getInt(RikoBook.KEY_BOOKS_CHAPNUM));	  

				/* Get publisher*/
				/* JSONObject publisherJsonObj = bookJsonObj.getJSONObject(RikoBook.KEY_BOOKS_PUBLISHER);
                Log.i("DBT", String.format("Publisher %s", publisherJsonObj));
                RikoPublisher publisher = new RikoPublisher();
                publisher.setId(publisherJsonObj.getInt(RikoBook.KEY_BOOKS_PUB_ID));
                publisher.setLon(publisherJsonObj.getString(RikoBook.KEY_BOOKS_PUB_LON));
                publisher.setCreateDate(publisherJsonObj.getString(RikoBook.KEY_BOOKS_PUB_DATE));
                publisher.setAddress(publisherJsonObj.getString(RikoBook.KEY_BOOKS_PUB_ADD));
                publisher.setStatus(publisherJsonObj.getString(RikoBook.KEY_BOOKS_PUB_STATUS));
                publisher.setLat(publisherJsonObj.getString(RikoBook.KEY_BOOKS_PUB_LAT));
                publisher.setName(publisherJsonObj.getString(RikoBook.KEY_BOOKS_PUB_NAME));
            	book.setPublisher(publisher);
				 */
				/*commentNum, priceSaleOff,fee,id, author,  
                /* system, title,price,likeNum,active, categories */	               

				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_COMMENT)){
					book.setCommentNum(bookJsonObj.getInt(RikoBook.KEY_BOOKS_COMMENT));
					Log.i("DBT", String.format("cmNum %d", bookJsonObj.getInt(RikoBook.KEY_BOOKS_COMMENT)));
				}
				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_PRICESALE)){
					book.setPriceSale(bookJsonObj.getString(RikoBook.KEY_BOOKS_PRICESALE));
					Log.i("DBT", String.format("price String", bookJsonObj.getString(RikoBook.KEY_BOOKS_PRICESALE)));
				}	      

				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_FEE)){
					book.setFee(bookJsonObj.getInt(RikoBook.KEY_BOOKS_FEE));
				}
				
				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_ID)){
					book.setId(bookJsonObj.getString(RikoBook.KEY_BOOKS_ID));
				}
				//  book.setAuthor(bookJsonObj.getString(RikoBook.KEY_BOOKS_AUTHOR));
				//  book.setSystem(bookJsonObj.getBoolean(RikoBook.KEY_BOOKS_SYSTEM));
				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_TITLE))
				{
					book.setTitle(bookJsonObj.getString(RikoBook.KEY_BOOKS_TITLE));
				}

				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_PRICE))
				{
					book.setPrice(bookJsonObj.getString(RikoBook.KEY_BOOKS_PRICE));
					Log.i("DBT", String.format("Price %s", bookJsonObj.getString(RikoBook.KEY_BOOKS_PRICE)));
				}

				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_LIKE))
				{
					book.setLikeNum(bookJsonObj.getInt(RikoBook.KEY_BOOKS_LIKE));
					Log.i("DBT", String.format("Like %d", bookJsonObj.getInt(RikoBook.KEY_BOOKS_LIKE)));
				}



				//  book.setActive(bookJsonObj.getBoolean(RikoBook.KEY_BOOKS_ACTIVE));

				//category
				/*     JSONArray  categorysArr = bookJsonObj.getJSONArray(RikoBook.KEY_BOOKS_CATE);
                if(categorysArr.length() > 0)
            	{
            		for(icate = 0; icate < categorysArr.length(); icate++)
	                {
	                	JSONObject cateObj = categorysArr.getJSONObject(icate);
	                	if(!TextUtils.isEmpty(cateObj.toString())){
	                		RikoCategory cate = new RikoCategory(cateObj.getInt(RikoBook.KEY_BOOKS_CATE_ID),
	                				cateObj.getString(RikoBook.KEY_BOOKS_CATE_NAME),
	                				cateObj.getInt(RikoBook.KEY_BOOKS_CATE_BOOKNUM),
	                				cateObj.getString(RikoBook.KEY_BOOKS_CATE_DATE));
	                		book.addCategories(cate);		
	                	}
	                }
            	}*/
				/* createDate, ranking, imageCover, completed, pageBookMark */
				// book.setCreateDate(bookJsonObj.getString(RikoBook.KEY_BOOKS_DATE));
				// Log.i("DBT", String.format("Date %s", bookJsonObj.getString(RikoBook.KEY_BOOKS_DATE)));
				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_RANKING)){
					book.setRanking(bookJsonObj.getInt(RikoBook.KEY_BOOKS_RANKING));
				}

				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_IMGCOVER)) {
					book.setImageCover(bookJsonObj.getString(RikoBook.KEY_BOOKS_IMGCOVER));
				}


				if(!bookJsonObj.isNull(RikoBook.KEY_BOOKS_BOOKMARK)) {
					book.setPageBookMark(bookJsonObj.getInt(RikoBook.KEY_BOOKS_BOOKMARK));
				} 

				//  book.setCompleted(bookJsonObj.getBoolean(RikoBook.KEY_BOOKS_COMPLETED));

				listbook.add(book);
			}	           
			Log.i("DBT", String.format("Return Listbook"));
			return listbook;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}				
	}

	public static ArrayList<RikoBook> getBookWithCategory (String auth, String userid)
	{ 	
		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("X-RIKO-Auth-Token",auth);
		headerParams.put("X-RIKO-USERID", userid);

		List<NameValuePair> getParams = new ArrayList<NameValuePair>();

		JSONObject jsonObj = connectByGetMethod(URL_BOOK_LIST_WITH_CATEGORY, headerParams, getParams);
		if (jsonObj == null)
			return null;
		ArrayList<RikoBook> listbook;
		listbook = getBookJsonObj(jsonObj);		
		return listbook;
	}

	public static ArrayList<RikoBook> getBookWithCategory (String auth, String userid, int cate, String id, String view, String like, String page)
	{
		if (TextUtils.isEmpty(id) && TextUtils.isEmpty(view) 
				&& TextUtils.isEmpty(like) && TextUtils.isEmpty(page) )
			return null;	
		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("X-RIKO-Auth-Token",auth);
		headerParams.put("X-RIKO-USERID", userid);
		List<NameValuePair> getParams = new ArrayList<NameValuePair>();
		switch(cate)
		{				
			case 1:
				getParams.add(new BasicNameValuePair(PARAM_KEY_VIEW, view));
				break;
			case 2:
				getParams.add(new BasicNameValuePair(PARAM_KEY_CATE_ID, id));
				break;			
			default:			
				break;
		}

		/*getParams.add(new BasicNameValuePair(PARAM_KEY_CATE_ID, id));
			getParams.add(new BasicNameValuePair(PARAM_KEY_VIEW, view));
			getParams.add(new BasicNameValuePair(PARAM_KEY_LIKE, like));
			getParams.add(new BasicNameValuePair(PARAM_KEY_PAGE, page));*/
		JSONObject jsonObj = connectByGetMethod(URL_BOOK_LIST_WITH_CATEGORY, headerParams, getParams);
		if (jsonObj == null)
			return null;
		ArrayList<RikoBook> listbook;
		listbook = getBookJsonObj(jsonObj);		
		return listbook;
	}

	public static ArrayList<RikoBook> getBookMyLibrary (String auth, String userid, int cate, String page, String limit)
	{	
		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("X-RIKO-Auth-Token",auth);
		headerParams.put("X-RIKO-USERID", userid);
		Log.i("DBT_TEST", String.format("MyLibrary userId=%s, authToken=%s", userid, auth));
		List<NameValuePair> getParams = new ArrayList<NameValuePair>();
		getParams.add(new BasicNameValuePair(PARAM_KEY_PAGE, page));
	/*  getParams.add(new BasicNameValuePair(PARAM_KEY_CATE_ID, id));
		getParams.add(new BasicNameValuePair(PARAM_KEY_VIEW, view));
		getParams.add(new BasicNameValuePair(PARAM_KEY_LIKE, like));
		getParams.add(new BasicNameValuePair(PARAM_KEY_PAGE, page));*/
		JSONObject jsonObj = connectByGetMethod(URL_GET_LIST_MY_LIB, headerParams, getParams);
		if (jsonObj == null)
			return null;
		ArrayList<RikoBook> listbook;
		listbook = getBookJsonObj(jsonObj);		
		return listbook;
	}

	public static int addBookToMyLibrary(String auth, String userid, String bookID, String number)
	{		
		if (TextUtils.isEmpty(auth) || TextUtils.isEmpty(userid) 
				|| TextUtils.isEmpty(bookID))
			return 0;

		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("X-RIKO-Auth-Token",auth);
		headerParams.put("X-RIKO-USERID", userid);
		
		Log.i("DBT_TEST", String.format("AddLibrary userId=%s, authToken=%s", userid, auth));
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(URL_ADD_LIBARY);
		MultipartEntity multipartEntity = new MultipartEntity();
		try {
			multipartEntity.addPart("data", new StringBody("data"));
			httpPost.setHeader("X-RIKO-Auth-Token",auth);
			httpPost.setHeader("X-RIKO-USERID", userid);
			multipartEntity.addPart(PARAM_KEY_BOOK_ID, new StringBody(bookID));
			multipartEntity.addPart(PARAM_KEY_NUMBER, new StringBody(number));
			httpPost.setEntity(multipartEntity);
			HttpResponse response = httpClient.execute(httpPost);
			JSONObject jsonObj = parseResponseToJson(response);
			
			if (jsonObj != null) {
				Log.i("LETRUONG", jsonObj.toString());
				try {
					if(jsonObj.isNull(RikoBook.KEY_BOOKS_STATUS))			
						return 0;
					if(jsonObj.getString(RikoBook.KEY_BOOKS_STATUS).equals(RIKO_STATUS_SUCCESS))
						return 1;
					return 0;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return 0;
				}
			}
			else
			{
				Log.i("DBT_TEST", String.format("Object NULL"));
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}
		return 0;
	}
	
	public static int deleteBookMyLibrary(String auth, String userid, String bookid, String number){
		
		if (TextUtils.isEmpty(auth) || TextUtils.isEmpty(userid)) 
			return 0;

		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("X-RIKO-Auth-Token",auth);
		headerParams.put("X-RIKO-USERID", userid);
		headerParams.put("Content-type","application/x-www-form-urlencoded");
		Log.i("DBT_TEST", String.format("ADdLibrary userId=%s, authToken=%s", userid, auth));
		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair(PARAM_KEY_USER_ID, userid));
		postParams.add(new BasicNameValuePair(PARAM_KEY_BOOK_ID, bookid));
		postParams.add(new BasicNameValuePair(PARAM_KEY_NUMBER, number));

		JSONObject jsonObj = connectByPostMethod(URL_COUNT_DELETE_BOOK_IN_LIB, headerParams, postParams);
		if (jsonObj != null) {
			try {
				if(jsonObj.isNull(RikoBook.KEY_BOOKS_STATUS))			
					return 0;
				if(jsonObj.getString(RikoBook.KEY_BOOKS_STATUS).equals(RIKO_STATUS_SUCCESS))
					return 1;
				return 0;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return 0;
			}
		}
		else
		{
			 Log.i("DBT_TEST", String.format("JSON NULL"));
			 return 0;
		}

	}

	/*********** GET BOOK WITH CATEGORY ***********/

	
	/********************************************/
	/* LETRUONG START*/
	public static Map<String, String> registerWithRikoServer(String name, String email, String password, String deviceID, String deviceToken) {
		if (TextUtils.isEmpty(name) || TextUtils.isEmpty(email) 
				|| TextUtils.isEmpty(password) || TextUtils.isEmpty(deviceID) )
			return null;

		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("Content-type","application/x-www-form-urlencoded");
		headerParams.put("X-RIKO-DEVID", deviceID);
		if (!TextUtils.isEmpty(deviceToken))
			headerParams.put("X-RIKO-DEVTOKEN", deviceToken);

		String passwordMD5 = CryptographyUtility.computeMD5Hash(password);
		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair(PARAM_KEY_USERNAME, name));
		postParams.add(new BasicNameValuePair(PARAM_KEY_EMAIL, email));
		postParams.add(new BasicNameValuePair(PARAM_KEY_PASSWORD, passwordMD5));

		JSONObject jsonObj = connectByPostMethod(URL_REGISTER, headerParams, postParams);
		if (jsonObj != null) {
			// A Simple JSONObject Parsing
			JSONArray nameArray = jsonObj.names();
			JSONArray valArray;
			try {
				Map<String, String> result = new HashMap<String, String>();
				valArray = jsonObj.toJSONArray(nameArray);
				for(int i=0;i<valArray.length();i++)
				{
					result.put(nameArray.getString(i), valArray.getString(i));
				}
				// pass to main activity to store password
				result.put(RIKO_RESULT_PASSWORD, password);
				// A Simple JSONObject Value Pushing
				return result;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}
	
	public static Map<String, String> loginWithRikoServer(String email, String password) {
		if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) )
			return null;
		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("Content-type","application/x-www-form-urlencoded");

		String passwordMD5 = CryptographyUtility.computeMD5Hash(password);

		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair(PARAM_KEY_EMAIL, email));
		postParams.add(new BasicNameValuePair(PARAM_KEY_PASSWORD, passwordMD5));
		Log.i(TAG_DEBUG, String.format("email=%s, password=%s,passwordMD5=%s", email, password, passwordMD5));
		JSONObject jsonObj = connectByPostMethod(URL_LOGIN, headerParams, postParams);
		if (jsonObj != null) {
			// A Simple JSONObject Parsing
			JSONArray nameArray = jsonObj.names();
			JSONArray valArray;
			try {
				Map<String, String> result = new HashMap<String, String>();
				valArray = jsonObj.toJSONArray(nameArray);
				for(int i=0;i<valArray.length();i++)
				{
					result.put(nameArray.getString(i), valArray.getString(i));
				}
				Log.i(TAG_DEBUG, String.format("Login_result_string", result.toString()));
				// pass to main activity to store password
				result.put(RIKO_RESULT_PASSWORD, password);
				// A Simple JSONObject Value Pushing
				return result;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}

	public static Map<String, String> loginFacebookWithRikoServer(String name, String email, String avatar, String periodToken, String fbId, String fbAccessToken, JSONArray fbFriends, String deviceID, String deviceToken) {
		if (TextUtils.isEmpty(name) || TextUtils.isEmpty(email)
				|| TextUtils.isEmpty(periodToken) || TextUtils.isEmpty(fbId) || TextUtils.isEmpty(fbAccessToken))
			return null;

		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("Content-type","application/x-www-form-urlencoded");
		headerParams.put("X-RIKO-DEVID", deviceID);
		if (!TextUtils.isEmpty(deviceToken))
			headerParams.put("X-RIKO-DEVTOKEN", deviceToken);

		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair(PARAM_KEY_USERNAME, name));
		postParams.add(new BasicNameValuePair(PARAM_KEY_EMAIL, email));
		if (!TextUtils.isEmpty(avatar))
			postParams.add(new BasicNameValuePair(PARAM_KEY_AVATAR, avatar));
		postParams.add(new BasicNameValuePair(PARAM_KEY_PERIOD_TOKEN, periodToken));
		postParams.add(new BasicNameValuePair(PARAM_KEY_FB_ID, fbId));
		postParams.add(new BasicNameValuePair(PARAM_KEY_FB_ACCESS_TOKEN, fbAccessToken));

		JSONObject jsonObj = connectByPostMethod(URL_LOGIN, headerParams, postParams);
		if (jsonObj != null) {
			// A Simple JSONObject Parsing
			JSONArray nameArray = jsonObj.names();
			JSONArray valArray;
			try {
				Map<String, String> result = new HashMap<String, String>();
				valArray = jsonObj.toJSONArray(nameArray);
				for(int i=0;i<valArray.length(); i++)
				{
					result.put(nameArray.getString(i), valArray.getString(i));
				}

				// A Simple JSONObject Value Pushing
				return result;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}

	public static boolean logoutWithRikoServer() {
		Map<String, String> headerParams = new HashMap<String, String>();

		List<NameValuePair> postParams = new ArrayList<NameValuePair>();

		JSONObject jsonObj = connectByPostMethod(URL_LOGOUT, headerParams, postParams);
		if (jsonObj != null) {
			// A Simple JSONObject Parsing
			if (!jsonObj.isNull(RIKO_RESULT_STATUS)) {
				Log.i("LETRUONG", String.format("logout_success=%s", jsonObj.toString()));
				try {
					return jsonObj.getString(RIKO_RESULT_STATUS).equals(RIKO_STATUS_SUCCESS) ? true : false;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return false;
				}
			}
			return false;

		}
		return false;
	}

	public static ArrayList<RikoCategory> getCategoryList (String auth, String userid)
	{
		Map<String, String> headerParams = new HashMap<String, String>();
		List<NameValuePair> getParams = new ArrayList<NameValuePair>();

		JSONObject jsonObj = connectByGetMethod(URL_GET_LIST_CATEGORY, headerParams, getParams);
		if (jsonObj != null) {
			// A Simple JSONObject Parsing

			ArrayList<RikoCategory> listCategory = new ArrayList<RikoCategory>();

			try {
				if(!jsonObj.getString(RikoBook.KEY_STATUS).equals(RIKO_STATUS_SUCCESS))
				{
					return null;
				}

				JSONArray  categoriesJsonArr = jsonObj.getJSONArray(RikoBook.KEY_BOOKS_CATE_LIST);

				for(int i = 0; i < categoriesJsonArr.length(); i++)
				{
					JSONObject categoryJsonObj = categoriesJsonArr.getJSONObject(i);
					RikoCategory category = new RikoCategory(categoryJsonObj.getInt(RikoBook.KEY_BOOKS_CATE_ID), categoryJsonObj.getString(RikoBook.KEY_BOOKS_CATE_NAME), 
							categoryJsonObj.getInt(RikoBook.KEY_BOOKS_CATE_BOOKNUM), categoryJsonObj.getString(RikoBook.KEY_BOOKS_CATE_IMAGE), 
							categoryJsonObj.getString(RikoBook.KEY_BOOKS_CATE_DATE));
					listCategory.add(category);
				}

				return listCategory;
			}
			catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}

	/* LETRUONG END*/
	/********************************************/

	
	/**
	 * @author HoangTuanSu
	 * @param auth
	 * @param userid
	 * @param path of the avatar
	 * @return true if success, otherwise, false
	 */
	public static Map<String, String> uploadAvatar(String auth, String userid, String path) {
		Map<String, String> headerParams = new HashMap<String, String>();
		headerParams.put("X-RIKO-Auth-Token",auth);
		headerParams.put("X-RIKO-USERID", userid);
		headerParams.put("Content-type","multipart/form-data");

		List<NameValuePair> postParams = new ArrayList<NameValuePair>();
		postParams.add(new BasicNameValuePair(PARAM_KEY_AVATAR, path));

		JSONObject jsonObj = connectByGetMethod(URL_UPLOAD_AVATAR, headerParams, postParams);
		if (jsonObj != null) {
			// A Simple JSONObject Parsing
			JSONArray nameArray = jsonObj.names();
			JSONArray valArray;
			try {
				Map<String, String> result = new HashMap<String, String>();
				valArray = jsonObj.toJSONArray(nameArray);
				for(int i=0;i<valArray.length();i++)
				{
					result.put(nameArray.getString(i), valArray.getString(i));
				}
				Log.i(TAG_DEBUG, String.format("Login_result_string", result.toString()));
				// A Simple JSONObject Value Pushing
				return result;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}
		return null;
	}
}
